package org.example.taskmaster.fragments;

import java.util.ArrayList;

import org.example.taskmaster.R;
import org.example.taskmaster.Task;
import org.example.taskmaster.activities.MainActivity;
import org.example.taskmaster.adapters.TaskListAdapter;
import org.example.taskmaster.database.DatabaseAdapter;
import org.example.taskmaster.sorters.Sorter;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ImageButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class TaskListFragment extends DetailsFragment implements OnClickListener{

	// references to views
	private TextView mLabel;
	private ListView mListView;
	private ImageButton mSortAlphabet;
	private ImageButton mSortDate;
	private ImageButton mSortCompleted;
	private ImageButton mShowCompleted;

	// sorter
	private Sorter sorter;
	// other values
	private boolean showComplete;
	private ArrayList<Long> mRowIDs; // array of rowIDs corresponding to list of tasks
	private String mList; // name of the list requested, or null for all Tasks
		
	public TaskListFragment() {
		this(null);
	}
	public TaskListFragment(String list) {
		type = "ListSelect";
		mList = list;
		showComplete = false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    // get database
		dbAdapter = new DatabaseAdapter(getActivity());
		dbAdapter.open();
		// set default sorter
		sorter = Sorter.getSorter(Sorter.DUE_DATE);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// create the View from the XML layout
		View mainView = inflater.inflate(R.layout.tasklist_fragment_layout, container, false);
      
        // get references to views
        mLabel = (TextView) mainView.findViewById(R.id.tasklist_label);
		mListView = (ListView) mainView.findViewById(R.id.tasklist_list);
		mSortAlphabet = (ImageButton) mainView.findViewById(R.id.tasklist_sortalphabetic);	// the Sort by Alphabet button
		mSortDate = (ImageButton) mainView.findViewById(R.id.tasklist_sortdate);	// the Sort by date button
		mSortCompleted = (ImageButton) mainView.findViewById(R.id.tasklist_sortcompleted);	// the Sort by completed button
		mShowCompleted = (ImageButton) mainView.findViewById(R.id.tasklist_showcompleted);	// the Sort by completed button

		// set page label, indicating what list is being shown
		if (mList != null) {
			mLabel.setText(mList);
		} else {
			mLabel.setText("All Tasks");
		}
		
		// registers self as listener for the sort strategy button
		mSortAlphabet.setOnClickListener(this);
		mSortDate.setOnClickListener(this);
		mSortCompleted.setOnClickListener(this);
		mShowCompleted.setOnClickListener(this);

		// switch image on 'show complete' button if it is on
		if (showComplete == true) {
			mShowCompleted.setImageResource(R.drawable.greencheck);
			mSortCompleted.setVisibility(View.VISIBLE);

		} else {
			mShowCompleted.setImageResource(R.drawable.greycheck);
			mSortCompleted.setVisibility(View.INVISIBLE);
		}
        
        // set listeners for List View
        mListView.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		// refer to MainActivity to load a task detail fragment into details area
        		MainActivity main = (MainActivity) getActivity();
        		main.showTaskDetail(mRowIDs.get((int) id));
        	}
        });
        mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        		long rowId = mRowIDs.get(position);
        		// toggle complete
        		dbAdapter.toggleComplete(rowId);
        		// refresh the list
        		populate();
        		return true;
        	}
        });
        
		// fill content of page from database
		this.populate();

		return mainView;
	}
	private void populate() {
		// get cursor for requested tasks from database
		cursor = dbAdapter.fetchTasksByList(mList, sorter.orderBy(), showComplete);

		// generate arrays of String representations of tasks
        ArrayList<String> names = new ArrayList<String>();
        //ArrayList<String> dates = new ArrayList<String>();
        ArrayList<Integer> complete = new ArrayList<Integer>();
        ArrayList<Integer> years = new ArrayList<Integer>();
        ArrayList<Integer> months = new ArrayList<Integer>();
        ArrayList<Integer> days = new ArrayList<Integer>();
        
        mRowIDs = new ArrayList<Long>();
        cursor.moveToFirst();
        while (cursor.isAfterLast() == false) { 
        	mRowIDs.add(cursor.getLong(0));
        	Task task = dbAdapter.getTask(cursor.getLong(0));//new Task(cursor);
        	names.add(task.getName());
        	years.add(task.getDueYear());
        	months.add(task.getDueMonth());
        	days.add(task.getDueDay());
        	//dates.add(task.getDueMonth() + "/" + task.getDueDay() + "/" + task.getDueYear());
        	complete.add(task.isComplete());
        	cursor.moveToNext();
        }
        // convert ArrayLists to simple arrays
        String[] task_list = names.toArray(new String[names.size()]);
        //String[] date_list = dates.toArray(new String[dates.size()]);
        Integer[] complete_list = complete.toArray(new Integer[complete.size()]);
        Integer[] years_list = years.toArray(new Integer[years.size()]);
        Integer[] months_list = months.toArray(new Integer[months.size()]);
        Integer[] days_list = days.toArray(new Integer[days.size()]);
        
        
        // set content of List View
        TaskListAdapter itemAdapter = new TaskListAdapter(getActivity(), task_list, days_list, months_list, years_list, complete_list);
        mListView.setAdapter(itemAdapter);

	}
	
	/**
	 * Select what sorting strategy to use
	 */
	@Override
	public void onClick(View v) {
		// if selecting a new sort strategy, reassign sorter. 
		// If selecting the existing sort strategy, just toggle the "descending" flag 
    	switch (v.getId()) {
		case R.id.tasklist_sortalphabetic:
			if (sorter.getType().equals(Sorter.ALPHABETIC)) {
				sorter.toggleDescending();
			} else {
				sorter = Sorter.getSorter(Sorter.ALPHABETIC);
			}
			break;
		case R.id.tasklist_sortdate:
			if (sorter.getType().equals(Sorter.DUE_DATE)) {
				sorter.toggleDescending();
			} else {
				sorter = Sorter.getSorter(Sorter.DUE_DATE);
			}
			break;
		case R.id.tasklist_sortcompleted:
			if (sorter.getType().equals(Sorter.COMPLETE)) {
				sorter.toggleDescending();
			} else {
				sorter = Sorter.getSorter(Sorter.COMPLETE);
			}
			break;
		case R.id.tasklist_showcompleted:
			showComplete = !showComplete;
			// update task-complete related buttons
			if (showComplete == true) {
				mShowCompleted.setImageResource(R.drawable.greencheck);
				mSortCompleted.setVisibility(View.VISIBLE);

			} else {
				mShowCompleted.setImageResource(R.drawable.greycheck);
				mSortCompleted.setVisibility(View.INVISIBLE);
			}
			break;
    	}

		populate();

	}

}
